package com.eshop.we.utils;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.eshop.we.account.entity.Account;
import com.eshop.we.business.UserBusiness;
import com.eshop.we.user.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CookieUtil {

    private  final String COOKIENAME="eshop";

    private  final String cookiePath="/";

    private  final Integer maxAge=360000;
    @Autowired
    private UserBusiness userBusiness;

    @Autowired
    private RedisUtil redis;

    public User getUesrByCookies(HttpServletRequest request){
        Cookie[] cookies=request.getCookies();
        if(cookies==null || cookies.length <=0){
            return null;
        }
        String cookValue="";
        for(Cookie cook:cookies){
            if(StringUtils.isNotBlank(cook.getName()) && COOKIENAME.equals(cook.getName())){
                cookValue=cook.getValue();
            }
        }
        if(StringUtils.isNotBlank(cookValue)){
           return userBusiness.selectOne(new EntityWrapper<User>().eq("login_token",cookValue).eq("is_del",0));
        };
        return  null;
    }

    public  void addCookieUser(HttpServletResponse response, String tokenId) {
        Cookie cookie = new Cookie(COOKIENAME, tokenId);
        cookie.setPath(cookiePath);
        if(maxAge>0)  cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }


}
